package fr.pentalog.ctc.dao.impl;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import fr.pentalog.ctc.dao.ItemDao;
import fr.pentalog.ctc.model.record.ItemRecord;
import fr.pentalog.ctc.util.GenericConstants;


/**
 * @author Danut Chindris
 * @since September 14, 2013
 */

@Repository
public class ItemDaoImpl extends BaseDaoImpl implements ItemDao {

	@SuppressWarnings("unchecked")
	@Transactional
	public List<ItemRecord> getMostRecentItems(Integer itemsNumber) throws HibernateException {
		StringBuilder sb = new StringBuilder();
		sb.append(" select new fr.pentalog.ctc.model.record.ItemRecord( ");
		sb.append(" i.id, i.title, i.addedDate, i.postalCode, r.name, i.description, i.pictureUrl, i.price ) ");
		sb.append(" from Item i ");
		sb.append(" inner join i.region r ");
		sb.append(" order by i.addedDate desc ");
		Query query = this.getCurrentSession().createQuery(sb.toString());
		if (itemsNumber != null && itemsNumber.intValue() != GenericConstants.ZERO) {
			query.setMaxResults(itemsNumber);
		}
		return query.list();
	}
}
